/*
 * This file is part of Cadmium.
 * Copyright (C) 2007-2010 Xavier Clerc.
 *
 * Cadmium is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Cadmium is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package fr.x9c.cadmium.primitives.unix;

import fr.x9c.cadmium.kernel.Block;
import fr.x9c.cadmium.kernel.CodeRunner;
import fr.x9c.cadmium.kernel.Context;
import fr.x9c.cadmium.kernel.Primitive;
import fr.x9c.cadmium.kernel.PrimitiveProvider;
import fr.x9c.cadmium.kernel.Value;
import fr.x9c.cadmium.util.Signal;

/**
 * This class provides implementation for timer-related primitives.
 *
 * @author <a href="mailto:cadmium@x9c.fr">Xavier Clerc</a>
 * @version 1.0
 * @since 1.0
 */
@PrimitiveProvider
public final class Itimer {

    /** Slots for timers. */
    private static final Object[] SLOTS = {
        new Object(),
        new Object(),
        new Object()
    };

    /** Signals to be sent by timers. */
    private static final Signal.Kind[] SIGNALS = {
        Signal.Kind.ALRM,
        Signal.Kind.VTALRM,
        Signal.Kind.PROF
    };

    /**
     * No instance of this class.
     */
    private Itimer() {
    } // end empty constructor

    /**
     * Sets a timer.
     * @param ctxt context
     * @param which timer to set
     * @param newVal timer parameter
     * @return current timer status
     */
    @Primitive
    public static Value unix_setitimer(final CodeRunner ctxt,
                                       final Value which,
                                       final Value newVal) {
        final Block newValBlock = newVal.asBlock();
        final long interval = (long) (newValBlock.getDouble(0) * 1000.0);
        final long value = (long) (newValBlock.getDouble(1) * 1000.0);
        final Context c = ctxt.getContext();
        final int w = which.asLong();
        final Unix.AlarmThread old = (Unix.AlarmThread) c.getSlot(Itimer.SLOTS[w]);
        final long resInterval;
        final long resValue;
        if (old != null) {
            resInterval = old.getInterval();
            resValue = old.unactivate();
        } else {
            resInterval = 0;
            resValue = 0;
        } // end if/else
        if (value != 0) {
            c.registerSlot(Itimer.SLOTS[w],
                           new Unix.AlarmThread(ctxt,
                                                value,
                                                interval,
                                                Itimer.SIGNALS[w]));
        } // end if
        return createStatus(resInterval, resValue);
    } // end method 'unix_setitimer(CodeRunner, Value, Value)'

    /**
     * Returns the status of a timer.
     * @param ctxt context
     * @param which timer to query
     * @return timer status
     */
    @Primitive
    public static Value unix_getitimer(final CodeRunner ctxt,
                                       final Value which) {
        final Unix.AlarmThread old =
            (Unix.AlarmThread) ctxt.getContext().getSlot(Itimer.SLOTS[which.asLong()]);
        final long resInterval;
        final long resValue;
        if (old != null) {
            resInterval = old.getInterval();
            resValue = old.getValue();
        } else {
            resInterval = 0;
            resValue = 0;
        } // end if/else
        return createStatus(resInterval, resValue);
    } // end method 'unix_getitimer(CodeRunner, Value)'

    /**
     * Constructs a value of <i>Unix.interval_timer_status</i> type from
     * fields content.
     * @param interval interval in milliseconds
     * @param value value in milliseconds
     * @return record constructed from passed time values
     */
    private static Value createStatus(final long interval, final long value) {
        final Block res = Block.createDoubleArray(2);
        res.setDouble(0, ((double) interval) / Unix.MILLISECS_PER_SEC);
        res.setDouble(1, ((double) value) / Unix.MILLISECS_PER_SEC);
        return Value.createFromBlock(res);
    } // end method 'createStatus(long, long)'

} // end class 'Itimer'
